from logging import getLogger

from zope.interface import Interface
from zope.schema import TextLine, Bool
from zope.component import getGlobalSiteManager

from meercat.harvester.base.interfaces import IHarvester
from meercat.harvester.voyager import VoyagerHarvester



log = getLogger('meercat.harvester.voyager.zcml')

class IVoyagerHarvesterSchema(Interface):
    name = TextLine(
        title=u'Name',
        description=u'The name of the harvester',
        required=True)
    
    schema = TextLine(
        title=u'Schema',
        description=u'The connection schema for the harvester i.e. oracle://user:pass@host/db',
        required=True)
    
    source = TextLine(
        title=u'Source Name',
        description=u'If necessary, you can specify a different source name for the harvester',
        required=False)
    
    null_pool = Bool(
        title=u'Null Pool',
        description=u'Should the harvester use the null pool class (necessary for multi-processing',
        required=False,
        default=False)

def harvester(context, name, schema, source=None, null_pool=False):
    log.debug('Registering voyager harvester: name=%s, schema=%s, null_pool=%s' % (str(name),
                                                                                   str(schema),
                                                                                   str(null_pool)))
    
    if not source:
        source = name
    
    kwargs = {'encoding': 'utf-8'}
    
    if null_pool:
        from sqlalchemy.pool import NullPool
        kwargs['poolclass'] = NullPool
            
    getGlobalSiteManager().registerUtility(provided=IHarvester, name=name,
                                           component=VoyagerHarvester(source,
                                                                      str(schema),
                                                                      **kwargs))
